package online.foxnull2.foxmall.ware.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import online.foxnull2.common.to.mq.OrderTo;
import online.foxnull2.common.to.mq.StockLockedTo;
import online.foxnull2.foxmall.ware.service.WareSkuService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@RabbitListener(queues = "stock.release.stock.queue")
@Service
public class StockReleaseListener {

    private final WareSkuService wareSkuService;

    @Autowired
    public StockReleaseListener(WareSkuService wareSkuService) {
        this.wareSkuService = wareSkuService;
    }

    @RabbitHandler
    public void stockReleaseHandle(StockLockedTo stockLockedTo, Message message, Channel channel) throws IOException {
        log.debug("stockReleaseHandle start");
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            wareSkuService.stockReleaseHandle(stockLockedTo);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            channel.basicReject(deliveryTag, true);
        }
        log.debug("stockReleaseHandle end");
    }

    @RabbitHandler
    public void orderReleaseHandle(OrderTo orderTo, Message message, Channel channel) throws IOException {
        log.debug("orderReleaseHandle start");
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            wareSkuService.stockReleaseHandle(orderTo);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            channel.basicReject(deliveryTag, true);
        }
        log.debug("orderReleaseHandle end");
    }
}
